//
//  RenewalsViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/9/18.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "RenewalsViewController.h"
#import "MallRequestManager.h"
#import "MoneyPayViewController.h"
#import "YearSelectedViewController.h"
#import "TransactionDetailsViewController.h"
#import "CLUIBaseTableViewController+Empty.h"
@interface RenewalsViewController ()
{
    MoneyPayViewController *_MoneyPayVC;
}
@property (weak, nonatomic) IBOutlet UILabel *labCost;
@property (weak, nonatomic) IBOutlet UILabel *labYears;
@property (weak, nonatomic) IBOutlet UIButton *btnInput;
@property (nonatomic,strong)UIButton *btnView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)NSMutableDictionary *orderDic;
@end

@implementation RenewalsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"服务费缴纳";
    [self showNavgationWithLeftItemWithTitle:@"返回"];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushToHistoryVC) name:@"FromRenewalsVCPushHistoryVC" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(removeMoneyPayVC) name:@"removeMoneyPayVCFromType2" object:nil];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.btnInput.enabled = NO;
    self.btnInput.backgroundColor = [UIColor orangeColor];
    self.btnInput.layer.cornerRadius = 21.0;
    self.btnInput.layer.masksToBounds = YES;
    self.labCost.text = @"";
    self.labYears.text = @"";
    [self requestData];

}
- (void)dealloc
{
    NSLog(@"removeMoneyPayVCFromType2通知被移除,pushHistoryVC通知被移除");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"removeMoneyPayVCFromType2" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"pushHistoryVC" object:nil];
}
- (void)removeMoneyPayVC
{
    [_MoneyPayVC.view removeFromSuperview];
    [self.btnView removeFromSuperview];
}
- (void)pushToHistoryVC
{
    [_MoneyPayVC.view removeFromSuperview];
    TransactionDetailsViewController *transactionDetails = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"TransactionDetailsViewController"];
    transactionDetails.orderId = [NSString stringWithFormat:@"%@",[self.orderDic objectForKey:@"orderid"]];
    transactionDetails.flag =@"2";
    [self.navigationController pushViewController:transactionDetails animated:YES];
}
- (void)requestData
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userID = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    [params setObject:userID forKey:@"user_id"];
    [params setObject:token forKey:@"token"];
    [SVProgressHUD showWithStatus:@"加载中"];
    [MallRequestManager post:@"Charge/service" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            
            [self performSelectorOnMainThread:@selector(showNetWorkError) withObject:nil waitUntilDone:YES];
            return ;
        }
        
        else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            if (dic !=nil) {
                NSDictionary *result = [dic objectForKey:@"result"];
                NSLog(@"dic:%@",result);
                self.dataSource = [result objectForKey:@"free_list"];
                [self performSelectorOnMainThread:@selector(loadUI) withObject:nil waitUntilDone:YES];
               
            }
        }
    }];
}
- (void)showNetWorkError
{
    self.tableView.allowsSelection  =NO;
     [self showLabelEmptyCate:CGRectMake((SCREEN_WIDTH - 100)/2, (SCREEN_HEIGHT -140 -64)/2, 100, 100) withTitle:@"出错了，稍后再试吧" withImage:[UIImage imageNamed:@"icon_wifi"]];
}
- (void)loadUI
{
    NSDictionary *dic = [self.dataSource objectAtIndex:0];
    self.labYears.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"year_num"]];
    self.labCost.text = [NSString stringWithFormat:@"￥%@",[dic objectForKey:@"total_fee"]];
    self.btnInput.enabled = YES;
}
- (IBAction)inputAction:(id)sender {
    [self orderaddRequest];//生成订单
    
}
- (void)orderaddRequest
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    [params setValue:userId forKey:@"user_id"];
    [params setObject:@"1" forKey:@"type"];
    [params setObject:self.labYears.text forKey:@"fee_num"];
    //生成订单
    [MallRequestManager post:@"Charge/orderadd" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (connectionError) {
            [SVProgressHUD showErrorWithStatus:@"请求失败"];
            return ;
        }else
        {
            if (dic !=nil) {

                if ([[dic objectForKey:@"message"]isEqualToString:@"提交成功"]) {
                    [SVProgressHUD showSuccessWithStatus:@"订单生成成功"];
                }
                if ([dic.allKeys containsObject:@"result"]) {
                   self.orderDic = [dic objectForKey:@"result"];
                    [self.orderDic setObject:@"2" forKey:@"type"];
                    [self performSelectorOnMainThread:@selector(showPayVC) withObject:nil waitUntilDone:YES];
                }
            }
        }
        
    }];
}
- (void)showPayVC
{
    
    //添加蒙层 弹出付款页面
    self.tableView.scrollEnabled =NO; //设置tableview 不能滚动
    self.btnView = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, self.tableView.frame.size.height)];
    self.btnView.backgroundColor = [UIColor grayColor];
    [self.btnView addTarget:self action:@selector(btnViewClicked) forControlEvents:UIControlEventTouchUpInside];
    self.btnView.alpha = 0.6f;
    [self.tableView addSubview:self.btnView];
    _MoneyPayVC = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"MoneyPay"];
    [self addChildViewController:_MoneyPayVC];
    _MoneyPayVC.view.frame = CGRectMake(0, self.tableView.contentSize.height-(self.tableView.contentSize.height-self.tableView.contentOffset.y-self.view.frame.size.height)-300, self.tableView.frame.size.width,300);
    _MoneyPayVC.view.alpha = 1.0;
    [self.tableView addSubview:_MoneyPayVC.view];
    _MoneyPayVC.flag = @"2";//2表示从服务费付款页跳转订单详情
    NSNotification *notification =[NSNotification notificationWithName:@"SubmitOrdersIsClicked" object:nil userInfo:self.orderDic];
    [[NSNotificationCenter defaultCenter] postNotification:notification];
}
- (void)btnViewClicked
{
    self.tableView.scrollEnabled =YES;
    [self.btnView removeFromSuperview];
    [_MoneyPayVC.view removeFromSuperview];
}
- (void)reloadUIWithYear:(NSDictionary *)year
{
    self.labYears.text = [NSString stringWithFormat:@"%@",[year objectForKey:@"year_num"]];
    self.labCost.text = [NSString stringWithFormat:@"￥%@",[year objectForKey:@"total_fee"]];
    [self.tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row ==0) {
            YearSelectedViewController *year = [[YearSelectedViewController alloc]init];
            year.dataArray = self.dataSource;
            [year returnText:^(NSDictionary *dic) {
                [self reloadUIWithYear:dic];
            }];
            [self.navigationController pushViewController: year animated:YES];
            
        }else
        {
            return;
        }
    }
    
}
@end
